"use client";

import React, { useState, useEffect } from "react";
import {
  Layout,
  List,
  Card,
  Pagination,
  Button,
  Spin,
  Typography,
  Space,
} from "antd";
import { LeftOutlined } from "@ant-design/icons";
import { useRouter } from "next/navigation";
import api from "../../utils/api";
import { useUser } from "../../context/userContext";

const { Content, Header } = Layout;
const { Text } = Typography;

const MessagePage = () => {
  const router = useRouter();
  const { user } = useUser();
  const [messages, setMessages] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalMessages, setTotalMessages] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [refreshKey, setRefreshKey] = useState(0); // 用于触发刷新的键

  // 监听refreshKey变化，重新获取消息
  useEffect(() => {
    fetchMessages(currentPage);
  }, [currentPage, refreshKey]);

  const fetchMessages = async (page) => {
    setLoading(true);
    setError(null);
    try {
      if (!user?.access_token) {
        throw new Error("用户未登录或令牌无效");
      }

      const response = await api.get("/alerts/getFromReceiver", {
        params: {
          page: page.toString(),
          pageSize: "10",
        },
        headers: {
          Authorization: `Bearer ${user.access_token}`,
        },
      });
      if (response.status === 200) {
        setMessages(response.data.alerts || []);
        setTotalMessages(response.data.total || 0);
      } else if (response.status === 401) {
        setError("用户未登录或令牌无效");
        console.error("用户未登录或令牌无效", err);
      }
    } catch (err) {
      setError("消息加载失败，请稍后重试");
      console.error("消息接口请求失败:", err);
    } finally {
      setLoading(false);
    }
  };

  // 单个消息标记为已读
  const markMessageAsRead = async (alertId) => {
    if (!user?.access_token) {
      return;
    }
    try {
      const markResponse = await api.put(
        `/alerts/read?alert_id=${alertId}`,
        {},
        {
          headers: {
            Authorization: `Bearer ${user.access_token}`,
          },
        }
      );

      if (markResponse.status === 200) {
        // 刷新消息列表
        setRefreshKey((prevKey) => prevKey + 1);
        return true;
      }
      return false;
    } catch (markErr) {
      console.error("标记消息为已读失败:", markErr);
      return false;
    }
  };

  // 标记所有消息为已读
  const markAllMessagesAsRead = async () => {
    if (!user?.access_token || messages.length === 0) {
      return;
    }

    const unreadMessages = messages.filter((msg) => msg.status === "unread");
    if (unreadMessages.length === 0) return;

    // 使用Promise.all并行处理多个请求
    const markPromises = unreadMessages.map((msg) =>
      api.put(
        `/alerts/read?alert_id=${msg.alert_id}`,
        {},
        {
          headers: {
            Authorization: `Bearer ${user.access_token}`,
          },
        }
      )
    );

    try {
      await Promise.all(markPromises);
      // 全部标记成功后刷新列表
      setRefreshKey((prevKey) => prevKey + 1);
    } catch (error) {
      console.error("批量标记消息为已读失败:", error);
    }
  };

  // 优化：在消息列表渲染完成后标记为已读
  useEffect(() => {
    if (messages.length > 0) {
      markAllMessagesAsRead();
    }
  }, [messages]);

  const handlePageChange = (newPage) => {
    setCurrentPage(newPage);
  };

  const renderMessageItem = (item) => {
    const isUnread = item.status === "unread";

    return (
      <List.Item
        key={item.alert_id}
        style={{
          border: "1px solid #e8e8e8",
          borderRadius: 6,
          padding: 18,
          marginBottom: 12,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          backgroundColor: isUnread ? "#f6ffed" : "#ffffff",
          transition: "background-color 0.3s",
        }}
      >
        <Space>
          {isUnread && (
            <span
              style={{
                width: 8,
                height: 8,
                borderRadius: "50%",
                backgroundColor: "#f5222d",
                display: "inline-block",
                marginRight: 8,
              }}
            />
          )}
          <Text style={{ fontSize: 16, color: isUnread ? "#111" : "#666" }}>
            {item.message || "无具体内容"}
          </Text>
        </Space>
        <Text type="secondary" style={{ fontSize: 10, color: "#999" }}>
          {new Date(item.createdAt).toLocaleString()}
        </Text>
      </List.Item>
    );
  };

  return (
    <Layout style={{ backgroundColor: "#ffffff66" }}>
      <Header
        style={{
          position: "sticky",
          top: 0,
          zIndex: 10,
          backgroundColor: "#ffffffaa",
          padding: "0 16px",
          height: 48,
        }}
      >
        {/* 返回按钮 */}
        <Button
          type="link"
          icon={<LeftOutlined />}
          onClick={() => router.back()}
          style={{ fontSize: 20, color: "#7a6e6e" }}
        >
          返回
        </Button>
      </Header>
      <Content style={{ padding: "16px", marginTop: 10 }}>
        {loading ? (
          <Spin
            style={{
              width: "100%",
              height: 10,
              display: "flex",
              justifyContent: "center",
            }}
          />
        ) : error ? (
          <Card style={{ padding: 16, color: "#f5222d", fontSize: 12 }}>
            {error}
          </Card>
        ) : (
          <>
            {/* 消息列表头部,消息导航 */}
            <Card
              style={{
                marginBottom: 16,
                padding: 4,
                backgroundColor: "#f9f9f9",
                borderRadius: 6,
              }}
            >
              <Text type="secondary" style={{ fontSize: 14, color: "#666" }}>
                共 {totalMessages} 条消息，当前第 {currentPage} 页
              </Text>
            </Card>
            {/* 消息列表 */}
            <List
              dataSource={messages}
              renderItem={renderMessageItem} // 渲染每个消息项
              itemLayout="horizontal"
              pagination={false}
            />
            {/* 分页组件 */}
            <Pagination
              current={currentPage}
              total={totalMessages}
              pageSize={10}
              onChange={handlePageChange}
              style={{
                marginTop: 24,
                display: "flex",
                justifyContent: "center",
              }}
            />
          </>
        )}
      </Content>
    </Layout>
  );
};

export default MessagePage;
